package com.example.webdownloadserver.base;

import com.example.webdownloadserver.service.TaskCenterService;
import com.example.webdownloadserver.vo.TaskCenter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 
 * <p>
 * 下载任务中心线程池
 * </p>
 * @title TaskDownloadThreadPool.java
 * @package com.dnkj.download.task.base 
 * @author ying.xiao
 * @version 0.1 2020年12月5日
 */
@Component
public class TaskDownloadThreadPool {

	private static Logger logger = LoggerFactory.getLogger(TaskDownloadThreadPool.class);

	private static final long THREAD_POOL_ID = System.currentTimeMillis();// 线程池id

	private static int POOL_SIZE = 10;// 默认线程池大小

	// 处理上传线程池,保证10个回执线程同时运行，其它的线程进入等待队列
	private static ThreadPoolExecutor downloadPool = new ThreadPoolExecutor(POOL_SIZE, 10, 1, TimeUnit.SECONDS,
			new ArrayBlockingQueue<Runnable>(200), new ThreadPoolExecutor.CallerRunsPolicy());

	public static void download(TaskCenterService taskCenterService, TaskCenter taskCenter) {
		downloadPool.execute(new TaskDownloadHandleThread(taskCenterService,taskCenter));
	}

	public static void close() {
		if ((downloadPool != null && !downloadPool.isShutdown())) {
			downloadPool.shutdown();
			logger.info("执行线程池回收成功.");
		}
	}

	/**
	 * 当前线程活跃线程数
	 * 
	 * @return
	 */
	public static int getActiveCount() {
		return downloadPool.getActiveCount();
	}

	/**
	 * 获取当线程池空余线程数
	 * 
	 * @return
	 */
	public static int getIdleNum() {
		int idle = POOL_SIZE - getActiveCount();
		return idle > 0 ? idle : 0;
	}

	/**
	 * 线程池id
	 * 
	 * @return
	 */
	public static long getThreadPoolId() {
		return THREAD_POOL_ID;
	}
}
